#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2020/12/14 下午2:44
# @Author  : HUANG Xiong
# @Site    : 
# @File    : stock_financial_related.py
# @Software: PyCharm 

"""
脚本说明：股票财务数据相关
"""
from quant_researcher.quant.project_tool.celebrity import get_lst_condition
from quant_researcher.quant.project_tool.db_operator import db_conn, my_mysql
from quant_researcher.quant.project_tool.logger.my_logger import LOG
from quant_researcher.quant.project_tool import time_tool
from quant_researcher.quant.datasource_fetch.stock_api.stock_info import get_stock_base_info

T_STOCK_DAILY_VALUATION = 'astk_fn_daily_valuation'
T_STOCK_FINANCIAL_INDICATORS = 'astk_fn_mainindicators'
T_STOCK_FINANCIAL_DERIVATIVE_INDICATORS = 'astk_fn_majorindicators_latest'
T_STOCK_BALANCE_INDICATORS = 'astk_fn_balance'
EARLIEST_START_DATE = '1900-01-01'


def get_stock_daily_valuation(stock_code, start_date, end_date, only_latest=False, select=None):
    """
    获得股票的市盈率、市净率等估值数据

    :param str or list or None stock_code: 股票代码，支持单个(str)多个(list)全部(None)
    :param str or int or datetime.date or datetime.datetime or int start_date: 开始时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param str or int or datetime.date or datetime.datetime or int end_date: 结束时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param bool only_latest: True-只获取最新的一天数据，False-获取一个区间段的数据
    :param list select: 需要返回哪些列，若为None，默认返回所有列
    :return: pd.DataFrame
                - info_pubdate: 信息发布时间 datetime
                - end_date: 交易日期 str
                - stock_code: 股票代码
                - total_mktval: 总市值
                - freefloat_mktval: 流通市值
                - pe: 市盈率
                - pe_ttm: 滚动市盈率
                - pb: 市净率
                - pcfa: 市现率(经营现金流)
                - pcfa_ttm: 滚动市现率(经营现金流)
                - pcfb: 市现率(现金流净额)
                - pcfb_ttm: 滚动市现率(现金流净额)
                - ps: 市销率
                - ps_ttm: 滚动市销率
                - div_rate: 股息率
                - div_ratettm: 滚动股息率
                - evebitda_a: 企业价值(含货币资金)
                - evebitda_b: 企业价值(剔除货币资金)
    """
    if select is not None:
        select = ['sec_code' if x == 'stock_code' else x for x in select]
        select = ['trade_date' if x == 'end_date' else x for x in select]

    where = []
    if isinstance(stock_code, str) or isinstance(stock_code, list):
        if isinstance(stock_code, str):
            stock_code = [stock_code]
        stock_where_condition = get_lst_condition(stock_code, 'sec_code')
        where.append(stock_where_condition)
    elif stock_code is None:
        stock_where_condition = '1 = 1'
    else:
        LOG.error('目前stock_code只支持str、list或者None，请按要求输入')
        raise NotImplementedError

    # 将日期转换成带杠字符串
    if start_date is None:
        start_date = EARLIEST_START_DATE.replace('-', '')
    else:
        start_date = time_tool.format_date_str(start_date, '%Y%m%d')
    if end_date is None:
        end_date = time_tool.get_today(marker='without_n_dash')
    else:
        end_date = time_tool.format_date_str(end_date, '%Y%m%d')

    conn = db_conn.get_stock_conn()

    if only_latest:
        if select is None:
            cols = '*'
        elif isinstance(select, list):
            cols = ', '.join(select)
        else:
            LOG.error(f"select参数为空或为list，请按要求输入")
            return
        sql_str = (f"select {cols} from {T_STOCK_DAILY_VALUATION} as a, "
                   f"(select sec_code as code, max(trade_date) as enddate "
                   f"from {T_STOCK_DAILY_VALUATION} "
                   f"where trade_date <= '{end_date}' "
                   f"and {stock_where_condition} "
                   f"group by sec_code) as b "
                   f"where a.sec_code = b.code "
                   f"and a.trade_date = b.enddate ")
        df = my_mysql.read_v3(sql_str, conn)
    else:
        where.append(f"trade_date >= '{start_date}'")
        where.append(f"trade_date <= '{end_date}'")
        df = my_mysql.read_v2(select=select, where=where, sfrom=T_STOCK_DAILY_VALUATION, conn=conn)

    conn.close()

    if df.empty:
        LOG.error('取出的数据为空，请检查输入')
        return

    if 'sec_code' in df.columns:
        df = df.rename(columns={'sec_code': 'stock_code'})
    if 'trade_date' in df.columns:
        df = df.rename(columns={'trade_date': 'end_date'})
        df['end_date'] = df['end_date'].apply(time_tool.format_date_str)

    if select is None:
        drop_column_list = ['tid', 'titime', 'tutime', 'tutimestamp',
                            'tcreator', 'tmodifier', 'tauditor', 'taudittime', 'tdatastate',
                            'tdatachannel', 'torigdatabuid']
        if only_latest:
            drop_column_list.extend(['code', 'enddate'])
        df.drop(columns=drop_column_list, inplace=True)

    return df


def get_stock_financial_indicators(stock_code=None, start_date=None, end_date=None,
                                   report_type=20, only_latest=True, select=None):
    """
    查询上市公司财务报告公布的主要财务指标数据

    :param str or list or None stock_code: 股票代码，支持单个(str)多个(list)全部(None)
    :param str or int or datetime.date or datetime.datetime or int start_date: 开始时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param str or int or datetime.date or datetime.datetime or int end_date: 结束时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param int or list report_type: 报告类型，10=发行上市书，20=定期报告，30=业绩快报，50=章程制度，70=临时公告，
                                            90=交易所通报，91=交易所临时停(复)牌公告，99=其他，默认20
    :param bool only_latest: True-只获取最新的一天数据，False-获取一个区间段的数据
    :param list select: 需要获得哪些列，默认：None（返回所有列）
    :return: pd.DataFrame
                - stock_code: 股票代码
                - info_pubdate: 信息发布时间 datetime
                - comp_code: 公司代码
                - report_date: 截止日期
                - accounting_standard: 会计准则，0=旧会计准则；1=新会计准则(2007)
                - report_type: 报告类型，10=发行上市书，20=定期报告，30=业绩快报，50=章程制度，70=临时公告，
                                       90=交易所通报，91=交易所临时停(复)牌公告，99=其他
                - merge_mark: 是否合并，1=合并，2=母公司，3=合并调整，4=母公司调整，5=合并修正前，6=母公司修正前，7=专项合并
                - eps_b: 基本每股收益(元)
                - eps_di: 稀释每股收益(元)
                - eps_bde: 基本每股收益(扣除)(元)
                - eps_dide: 稀释每股收益(扣除)(元)
                - eps_tb: 每股收益(摊薄)(元)
                - roe_tb: 净资产收益率(摊薄)(%)
                - roe_tbde: 净资产收益率(摊薄-扣除)(%)
                - roe_w: 净资产收益率(加权)(%)
                - roe_wde: 净资产收益率(加权-扣除)(%)
                - net_profit: 净利润(元)
                - minority_interest: 少数股东损益(元)
                - np_demi: 净利润(不含少数损益)(元)
                - nonre_pl: 非经常性损益(元)
                - np_denrpl: 扣除非经常性损益后净利润(元)
                - oncf_netamount: 经营活动产生的现金流量净额(元)
                - total_assets: 总资产(元)
                - she_deme: 股东权益(不含少数权益)(元)
                - minority_equity: 少数股东权益(元)
                - she_total: 所有者权益合计(元)
                - bvps: 每股净资产(元)
                - total_shares: 总股本(股)
                - allofin_desc: 分配融资方案说明
                - audit_opinion: 非标准审计意见描述
    """
    conn = db_conn.get_stock_conn()

    if start_date is None:
        start_date = EARLIEST_START_DATE.replace('-', '')
    else:
        start_date = time_tool.format_date_str(start_date, '%Y%m%d')
    if end_date is None:
        end_date = time_tool.get_today(marker='without_n_dash')
    else:
        end_date = time_tool.format_date_str(end_date, '%Y%m%d')

    select_origin = select.copy()
    if select is None:
        cols = '*'
    elif isinstance(select, list):
        select = ['rept_enddate' if x == 'report_date' else x for x in select]
        select = ['retp_type' if x == 'report_type' else x for x in select]
        if 'stock_code' in select:
            select.remove('stock_code')
        if 'comp_code' not in select:
            select.append('comp_code')
        cols = ', '.join(select)
    else:
        LOG.error(f"select参数为空或为list，请按要求输入")
        return

    stock_company_df = get_stock_base_info(None, select=['stock_code', 'comp_code'])

    if stock_code is None:
        company_list = list(stock_company_df['comp_code'].dropna().unique())
    else:
        if isinstance(stock_code, str):
            stock_code = [stock_code]
        company_list = list(stock_company_df[stock_company_df['stock_code'].isin(stock_code)]
                            ['comp_code'].dropna().unique())
    stock_where_condition = get_lst_condition(company_list, 'comp_code')

    # report_type过滤条件
    if isinstance(report_type, int):
        report_type = [report_type]
    elif isinstance(report_type, list):
        pass
    else:
        LOG.error('目前report_type只支持int、list，请按要求输入')
        raise NotImplementedError
    report_where_condition = get_lst_condition(report_type, 'retp_type')
    report_where_condition_4_sql = 'a.' + report_where_condition

    if only_latest:
        sql_str = (f"select {cols} from {T_STOCK_FINANCIAL_INDICATORS} as a, "
                   f"(select comp_code as code, max(rept_enddate) as enddate "
                   f"from {T_STOCK_FINANCIAL_INDICATORS} "
                   f"where rept_enddate <= '{end_date}' "
                   f"and {stock_where_condition} "
                   f"group by comp_code) as b "
                   f"where a.comp_code = b.code "
                   f"and a.rept_enddate = b.enddate "
                   f"and {report_where_condition_4_sql} ")
        df = my_mysql.read_v3(sql_str, conn)
    else:
        df = my_mysql.read_v2(select=select, sfrom=T_STOCK_FINANCIAL_INDICATORS,
                              where=[stock_where_condition,
                                     f"rept_enddate >= '{start_date}'",
                                     f"rept_enddate <= '{end_date}'",
                                     report_where_condition],
                              conn=conn)
    conn.close()

    if df.empty:
        LOG.error('取出的数据为空，请检查输入')
        return

    if select is None or 'stock_code' in select_origin:
        df = df.merge(stock_company_df, how='left', on='comp_code')

    # T_STOCK_FINANCIAL_INDICATORS表没有stock_code字段，是根据comp_code查询
    # 同一个comp_code可能对应多个stock_code，需要过滤
    if stock_code is not None:
        df = df[df['stock_code'].isin(stock_code)]

    if select is None:
        drop_column_list = ['tid', 'titime', 'tutime', 'tutimestamp',
                            'tcreator', 'tmodifier', 'tauditor', 'taudittime', 'tdatastate',
                            'tdatachannel', 'torigdatabuid']
        if only_latest:
            drop_column_list.extend(['code', 'enddate'])
        df.drop(columns=drop_column_list, inplace=True)

    if 'rept_enddate' in df.columns:
        df = df.rename(columns={'rept_enddate': 'report_date'})
        df['report_date'] = df['report_date'].apply(time_tool.format_date_str)

    if 'retp_type' in df.columns:
        df = df.rename(columns={'retp_type': 'report_type'})

    if 'comp_code' not in select_origin:
        df = df.drop(columns=['comp_code'])

    return df


def get_stock_financial_derivative_indicators(stock_code=None, start_date=None, end_date=None,
                                              only_latest=True, select=None):
    """
    查询上市公司各报告期财务科目衍生出来的反映公司的盈利能力,运营能力,成长性等财务指标

    :param str or list or None stock_code: 股票代码，支持单个(str)多个(list)全部(None)
    :param str or int or datetime.date or datetime.datetime or int start_date: 开始时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param str or int or datetime.date or datetime.datetime or int end_date: 结束时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param bool only_latest: True-只获取最新的一天数据，False-获取一个区间段的数据
    :param list select: 需要获得哪些列，默认：None（返回所有列）
    :return: pd.DataFrame
                - stock_code: 股票代码
                - info_pubdate: 信息发布时间 datetime
                - comp_code: 公司代码
                - report_date: 截止日期
                - eps: 基本每股收益(元/股)
                - eps_di: 稀释每股收益(元/股)
                - eps_tb: 每股收益_期末股本摊薄(元/股)
                - eps_ttm: 每股收益_TTM(元/股)
                - bps: 每股净资产(元/股)
                - totalincomeps: 每股营业总收入(元/股)
                - operaincomeps: 每股营业收入(元/股)
                - operaincomeps_ttm: 每股营业收入_TTM(元/股)
                - operaprofitps: 每股营业利润(元/股)
                - ebitps: 每股息税前利润(元/股)
                - captresvps: 每股资本公积金(元/股)
                - surpresvps: 每股盈余公积(元/股)
                - pubresvps: 每股公积金(元/股)
                - udpps: 每股未分配利润(元/股)
                - retainedps: 每股留存收益(元/股)
                - oacashnetps: 每股经营活动产生的现金流量净额(元/股)
                - oacashnetps_ttm: 每股经营活动产生的现金流量净额_TTM(元/股)
                - netcashflowps: 每股现金流量净额(元/股)
                - netcashflowps_ttm: 每股现金流量净额_TTM(元/股)
                - fcffps: 每股企业自由现金流量(元/股)
                - scffps: 每股股东自由现金流量(元/股)
                - roe_a: 净资产收益率_平均,计算值(%)
                - roe_w: 净资产收益率_加权,公布值(%)
                - roe_di: 净资产收益率_摊薄,公布值(%)
                - roe_dd: 净资产收益率_扣除,摊薄(%)
                - roe_dw: 净资产收益率_扣除,加权(%)
                - roe_ttm: 净资产收益率_TTM(%)
                - roa: 总资产报酬率(%)
                - roa_ttm: 总资产报酬率_TTM(%)
                - jroa: 总资产净利率(%)
                - jroa_ttm: 总资产净利率_TTM(%)
                - npm: 销售净利率(%)
                - npm_ttm: 销售净利率_TTM(%)
                - gpm: 销售毛利率(%)
                - gpm_ttm: 销售毛利率_TTM(%)
                - salecost_ratio: 销售成本率(%)
                - saleduring_ratio: 销售期间费用率(%)
                - saleduring_ratio_ttm: 销售期间费用率_TTM(%)
                - operincome_yoy: 营业收入同比增长(%)
                - netprofile_yoy: 净利润同比增长(%)
                - receivableto_ratio: 应收帐款周转率(次)
                - liquidity_ratio: 流动比率
                - oprnetcash_to_opin: 经营活动产生的现金流量净额/营业收入(%)
    """
    conn = db_conn.get_stock_conn()

    if start_date is None:
        start_date = EARLIEST_START_DATE.replace('-', '')
    else:
        start_date = time_tool.format_date_str(start_date, '%Y%m%d')
    if end_date is None:
        end_date = time_tool.get_today(marker='without_n_dash')
    else:
        end_date = time_tool.format_date_str(end_date, '%Y%m%d')

    select_origin = select.copy()
    if select is None:
        cols = '*'
    elif isinstance(select, list):
        select = ['rept_enddate' if x == 'report_date' else x for x in select]
        if 'stock_code' in select:
            select.remove('stock_code')
        if 'comp_code' not in select:
            select.append('comp_code')
        cols = ', '.join(select)
    else:
        LOG.error(f"select参数为空或为list，请按要求输入")
        return

    stock_company_df = get_stock_base_info(None, select=['stock_code', 'comp_code'])

    if stock_code is None:
        company_list = list(stock_company_df['comp_code'].dropna().unique())
    else:
        if isinstance(stock_code, str):
            stock_code = [stock_code]
        company_list = list(stock_company_df[stock_company_df['stock_code'].isin(stock_code)]
                            ['comp_code'].dropna().unique())
    stock_where_condition = get_lst_condition(company_list, 'comp_code')

    if only_latest:
        sql_str = (f"select {cols} from {T_STOCK_FINANCIAL_DERIVATIVE_INDICATORS} as a, "
                   f"(select comp_code as code, max(rept_enddate) as enddate "
                   f"from {T_STOCK_FINANCIAL_DERIVATIVE_INDICATORS} "
                   f"where rept_enddate <= '{end_date}' "
                   f"and {stock_where_condition} "
                   f"group by comp_code) as b "
                   f"where a.comp_code = b.code "
                   f"and a.rept_enddate = b.enddate ")
        df = my_mysql.read_v3(sql_str, conn)
    else:
        df = my_mysql.read_v2(select=select, sfrom=T_STOCK_FINANCIAL_DERIVATIVE_INDICATORS,
                              where=[stock_where_condition,
                                     f"rept_enddate >= '{start_date}'",
                                     f"rept_enddate <= '{end_date}'"],
                              conn=conn)
    conn.close()

    if df.empty:
        LOG.error('取出的数据为空，请检查输入')
        return

    if select is None or 'stock_code' in select_origin:
        df = df.merge(stock_company_df, how='left', on='comp_code')

    # T_STOCK_FINANCIAL_DERIVATIVE_INDICATORS表没有stock_code字段，是根据comp_code查询
    # 同一个comp_code可能对应多个stock_code，需要过滤
    if stock_code is not None:
        df = df[df['stock_code'].isin(stock_code)]

    if select is None:
        drop_column_list = ['tid', 'titime', 'tutime', 'tutimestamp',
                            'tcreator', 'tmodifier', 'tauditor', 'taudittime', 'tdatastate',
                            'tdatachannel', 'torigdatabuid']
        if only_latest:
            drop_column_list.extend(['code', 'enddate'])
        df.drop(columns=drop_column_list, inplace=True)

    if 'rept_enddate' in df.columns:
        df = df.rename(columns={'rept_enddate': 'report_date'})
        df['report_date'] = df['report_date'].apply(time_tool.format_date_str)

    if 'comp_code' not in select_origin:
        df = df.drop(columns=['comp_code'])

    return df


def get_stock_balance_indicators(stock_code=None, start_date=None, end_date=None,
                                 report_type=20, only_latest=True, select=None):
    """
    查询沪深上市公司定期报告中披露的资产负债表数据情况

    :param str or list or None stock_code: 股票代码，支持单个(str)多个(list)全部(None)
    :param str or int or datetime.date or datetime.datetime or int start_date: 开始时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param str or int or datetime.date or datetime.datetime or int end_date: 结束时间，支持带杠字符串、不带杠字符串、datetime、date、int格式
    :param int or list report_type: 报告类型，10=发行上市书，20=定期报告，30=业绩快报，50=章程制度，70=临时公告，
                                            90=交易所通报，91=交易所临时停(复)牌公告，99=其他，默认20
    :param bool only_latest: True-只获取最新的一天数据，False-获取一个区间段的数据
    :param list select: 需要获得哪些列，默认：None（返回所有列）
    :return: pd.DataFrame
                - stock_code: 股票代码
                - info_pubdate: 信息发布时间
                - comp_code: 公司代码
                - report_date: 截止日期
                - report_type: 报表类别
                - accounting_standard: 会计准则，0=旧会计准则,1=新会计准则(2007)
                - enterprise_nature: 企业性质，13=商业银行,31=证券公司,33=信托公司,35=保险公司,39=其他非银行金融机构,99=一般企业
                - is_merged: 是否合并，1=合并,2=母公司,3=合并调整,4=母公司调整,5=合并修正前,6=母公司修正前,7=专项合并
                - is_adjusted: 是否调整，1=是,2=否,6=一季末调整,7=二季末调整,8=三季末调整
                - is_complete: 完整标志，1=完整报表,2=简表,3=个别字段修正报表
                - currency_fund: 货币资金
                - custfnd_deposit: 其中:客户资金存款
                - trading_assets: 交易性金融资产
                - bill_receivable: 应收票据
                - dividend_receivable: 应收股利
                - billacc_Receivable: 应收票据及应收账款
                - interest_receivable: 应收利息
                - account_receivable: 应收账款
                - contract_assets: 合同资产
                - other_receivable: 其他应收款
                - other_receivableind: 其他应收款(含利息和股利)
                - advance_payment: 预付款项
                - receivables_fin: 应收款项融资
                - finLease_Receivable: 应收融资租赁款
                - inventories: 存货
                - invtrs_cbasset: 其中:消耗性生物资产
                - Deferred_Expense: 待摊费用
                - hfsale_assets: 划分为持有待售的资产
                - noncurasset_moy: 一年内到期的非流动资产
                - other_curassets: 其他流动资产
                - curasset_spitems: ——流动资产特殊项目
                - curasset_adjitems: ——流动资产调整项目
                - total_curassets: 流动资产合计
                - debt_invt: 债权投资
                - othdebt_invt: 其他债权投资
                - holdtomt_invt: 持有至到期投资
                - holdfsale_sssets: 可供出售金融资产
                - otheqinstru_invt: 其他权益工具投资
                - othnoncur_finassets: 其他非流动金融资产
                - investment_property: 投资性房地产
                - longterm_eqinvt: 长期股权投资
                - longterm_recaccount: 长期应收款
                - fixed_assets: 固定资产
                - project_material: 工程物资
                - constru_inprocess: 在建工程
                - fixedassets_disposal: 固定资产清理
                - biological_assets: 生产性生物资产
                - oilgas_assets: 油气资产
                - intangible_assets: 无形资产
                - seat_costs: 其中:交易席位费
                - development_expenditure: 开发支出
                - usufruct_assets: 使用权资产
                - goodwill: 商誉
                - longdeferred_expense: 长期待摊费用
                - deferredtax_assets: 递延所得税资产
                - other_noncurassets: 其他非流动资产
                - noncurasset_spitems: ——非流动资产特殊项目
                - noncurasset_adjitems: ——非流动资产调整项目
                - total_noncurasset: 非流动资产合计
                - loan_recaccount: 投资-贷款及应收款项(应收款项类投资)
                - financing: 融出资金
                - cesconres_receivable: 应收分保合同准备金
                - settlement_funds: 结算备付金
                - customer_reserves: 其中:客户备付金
                - deposit_ininterbank: 存放同业款项
                - precious_metal: 贵金属
                - lending_funds: 拆出资金
                - derivative_assets: 衍生金融资产
                - redemptory_finassets: 买入返售金融资产
                - loan_advance: 发放贷款和垫款
                - insurance_receivable: 应收保费
                - subrogationfee_receivable: 应收代位追偿款
                - reinsurance_receivable: 应收分保账款
                - unearnedr_receivable: 应收分保未到期责任准备金
                - claimsr_receivable: 应收分保未决赔款准备金
                - lifer_receivable: 应收分保寿险责任准备金
                - thealthr_receivablel: 应收分保长期健康险责任准备金
                - insurer_impawnloan: 保户质押贷款
                - fixedterm_deposit: 定期存款
                - refundable_deposit: 存出保证金
                - recapital_deposit: 存出资本保证金
                - independence_accassets: 独立账户资产
                - other_assets: 其他资产
                - asset_spitems: 资产特殊项目
                - asset_adjustitems: 资产调整项目
                - total_assets: 资产总计
                - shortterm_loan: 短期借款
                - impawned_loan: 其中:质押借款
                - trading_liability: 交易性金融负债
                - notes_payable: 应付票据
                - accounts_payable: 应付账款
                - noteacc_payable: 应付票据及应付账款
                - contract_liability: 合同负债
                - stbonds_payable: 应付短期债券
                - advance_receipts: 预收款项
                - salaries_payable: 应付职工薪酬
                - dividend_payable: 应付股利
                - taxs_payable: 应交税费
                - interest_payable: 应付利息
                - other_payable: 其他应付款
                - other_payableind: 其他应付款(含利息和股利)
                - accrued_expense: 预提费用
                - deferred_income: 递延收益
                - holdforsale_liability: 划分为持有待售的负债
                - noncurliability_inoneyear: 一年内到期的非流动负债
                - other_curliability: 其他流动负债
                - curliability_spitems: ——流动负债特殊项目
                - curliability_adjitems: ——流动负债调整项目
                - total_curliability: 流动负债合计
                - longterm_loan: 长期借款
                - bonds_payable: 应付债券
                - bp_preferstock: ——优先股
                - bp_perpetualdebt: ——永续债
                - longtermacc_payable: 长期应付款
                - ltsalary_payable: 长期应付职工薪酬
                - spaccount_payable: 专项应付款
                - estimate_liability: 预计负债
                - deferredtax_liability: 递延所得税负债
                - lease_liability: 租赁负债
                - finleases_payable: 应付融资租赁款
                - ltdefer_income: 长期递延收益
                - othernoncur_liability: 其他非流动负债
                - othernoncur_spitems: ——非流动负债特殊项目
                - othernoncur_adjitems: ——非流动负债调整项目
                - totalnoncur_liability: 非流动负债合计
                - borrowing_fromcenbank: 向中央银行借款
                - depositloant_otherbank: 同业及其他金融机构存放款项
                - borrowing_funds: 拆入资金
                - derivative_liability: 衍生金融负债
                - sell_rofa: 卖出回购金融资产款
                - accept_deposit: 吸收存款
                - acttrdsec_funds: 代理买卖证券款
                - actunder_funds: 代理承销证券款
                - deposits_received: 存入保证金
                - advance_insurance: 预收保费
                - commission_payable: 应付手续费及佣金
                - reinsurance_payable: 应付分保账款
                - compensation_payable: 应付赔付款
                - bonus_payable: 应付保单红利
                - acceptinter_deposits: 吸收存款及同业存款
                - inscontract_reserves: 保险合同准备金
                - insurerdeposit_investment: 保户储金及投资款
                - unearnedpremium_reserves: 未到期责任准备金
                - outstandingclaim_reserves: 未决赔款准备金
                - lifeins_reserves: 寿险责任准备金
                - ltheathins_reserves: 长期健康险责任准备金
                - independence_liability: 独立账户负债
                - other_liability: 其他负债
                - liability_spitems: 负债特殊项目
                - liability_adjitems: 负债调整项目
                - total_liability: 负债合计
                - paidin_capital: 实收资本(或股本)
                - other_eqinstru: 其他权益工具
                - oei_preferstock: ——优先股
                - oei_perpetualdebt: ——永续债
                - capital_reserves: 资本公积
                - surplus_reserves: 盈余公积
                - retained_profit: 未分配利润
                - treasury_stock: 减:库存股
                - othercomposite_income: 其他综合收益
                - comrisk_reserves: 一般风险准备
                - traderisk_reserves: 交易风险准备
                - translation_reserve: 外币报表折算差额
                - unrealised_invtloss: 未确认投资损失
                - other_reserves: 其他储备(公允价值变动储备)
                - specific_reserves: 专项储备
                - parentcompeq_spitems: ——归属母公司所有者权益特殊项目
                - parentcompeq_adjitems: ——归属母公司所有者权益调整项目
                - parentcompeq_total: 归属母公司股东权益合计
                - minority_equity : 少数股东权益
                - otheritemseffectingse: 所有者权益调整项目
                - total_shareholdeq: 所有者权益(或股东权益)合计
                - le_spitems: ——负债和权益特殊项目
                - le_adjitems: ——负债和权益调整项目
                - total_le: 负债和所有者权益(或股东权益)总计
                - spfield_desc: 特殊字段说明
    """
    conn = db_conn.get_stock_conn()

    if start_date is None:
        start_date = EARLIEST_START_DATE.replace('-', '')
    else:
        start_date = time_tool.format_date_str(start_date, '%Y%m%d')
    if end_date is None:
        end_date = time_tool.get_today(marker='without_n_dash')
    else:
        end_date = time_tool.format_date_str(end_date, '%Y%m%d')

    select_origin = select.copy()
    if select is None:
        cols = '*'
    elif isinstance(select, list):
        select = ['rept_enddate' if x == 'report_date' else x for x in select]
        select = ['retp_type' if x == 'report_type' else x for x in select]
        if 'stock_code' in select:
            select.remove('stock_code')
        if 'comp_code' not in select:
            select.append('comp_code')
        cols = ', '.join(select)
    else:
        LOG.error(f"select参数为空或为list，请按要求输入")
        return

    stock_company_df = get_stock_base_info(None, select=['stock_code', 'comp_code'])

    if stock_code is None:
        company_list = list(stock_company_df['comp_code'].dropna().unique())
    else:
        if isinstance(stock_code, str):
            stock_code = [stock_code]
        company_list = list(stock_company_df[stock_company_df['stock_code'].isin(stock_code)]
                            ['comp_code'].dropna().unique())
    stock_where_condition = get_lst_condition(company_list, 'comp_code')

    # report_type过滤条件
    if isinstance(report_type, int):
        report_type = [report_type]
    elif isinstance(report_type, list):
        pass
    else:
        LOG.error('目前report_type只支持int、list，请按要求输入')
        raise NotImplementedError
    report_where_condition = get_lst_condition(report_type, 'retp_type')
    report_where_condition_4_sql = 'a.' + report_where_condition

    if only_latest:
        sql_str = (f"select {cols} from {T_STOCK_BALANCE_INDICATORS} as a, "
                   f"(select comp_code as code, max(rept_enddate) as enddate "
                   f"from {T_STOCK_BALANCE_INDICATORS} "
                   f"where rept_enddate <= '{end_date}' "
                   f"and {stock_where_condition} "
                   f"group by comp_code) as b "
                   f"where a.comp_code = b.code "
                   f"and a.rept_enddate = b.enddate "
                   f"and {report_where_condition_4_sql} ")
        df = my_mysql.read_v3(sql_str, conn)
    else:
        df = my_mysql.read_v2(select=select, sfrom=T_STOCK_BALANCE_INDICATORS,
                              where=[stock_where_condition,
                                     f"rept_enddate >= '{start_date}'",
                                     f"rept_enddate <= '{end_date}'",
                                     report_where_condition],
                              conn=conn)
    conn.close()

    if df.empty:
        LOG.error('取出的数据为空，请检查输入')
        return

    if select is None or 'stock_code' in select_origin:
        df = df.merge(stock_company_df, how='left', on='comp_code')

    # T_STOCK_BALANCE_INDICATORS表没有stock_code字段，是根据comp_code查询
    # 同一个comp_code可能对应多个stock_code，需要过滤
    if stock_code is not None:
        df = df[df['stock_code'].isin(stock_code)]

    if select is None:
        drop_column_list = ['tid', 'titime', 'tutime', 'tutimestamp',
                            'tcreator', 'tmodifier', 'tauditor', 'taudittime', 'tdatastate',
                            'tdatachannel', 'torigdatabuid']
        if only_latest:
            drop_column_list.extend(['code', 'enddate'])
        df.drop(columns=drop_column_list, inplace=True)

    if 'rept_enddate' in df.columns:
        df = df.rename(columns={'rept_enddate': 'report_date'})
        df['report_date'] = df['report_date'].apply(time_tool.format_date_str)

    if 'retp_type' in df.columns:
        df = df.rename(columns={'retp_type': 'report_type'})

    if 'comp_code' not in select_origin:
        df = df.drop(columns=['comp_code'])

    return df


financial_dict = {

    # 1.每股指标
    '001基本每股收益': 'EPS',
    '002扣除非经常性损益每股收益': 'deductEPS',
    '003每股未分配利润': 'undistributedProfitPerShare',
    '004每股净资产': 'netAssetsPerShare',
    '005每股资本公积金': 'capitalReservePerShare',
    '006净资产收益率': 'ROE',
    '007每股经营现金流量': 'operatingCashFlowPerShare',
    # 2. 资产负债表 BALANCE SHEET
    # 2.1 资产
    # 2.1.1 流动资产
    '008货币资金': 'moneyFunds',
    '009交易性金融资产': 'tradingFinancialAssets',
    '010应收票据': 'billsReceivables',
    '011应收账款': 'accountsReceivables',
    '012预付款项': 'prepayments',
    '013其他应收款': 'otherReceivables',
    '014应收关联公司款': 'interCompanyReceivables',
    '015应收利息': 'interestReceivables',
    '016应收股利': 'dividendsReceivables',
    '017存货': 'inventory',
    '018其中：消耗性生物资产': 'expendableBiologicalAssets',
    '019一年内到期的非流动资产': 'noncurrentAssetsDueWithinOneYear',
    '020其他流动资产': 'otherLiquidAssets',
    '021流动资产合计': 'totalLiquidAssets',
    # 2.1.2 非流动资产
    '022可供出售金融资产': 'availableForSaleSecurities',
    '023持有至到期投资': 'heldToMaturityInvestments',
    '024长期应收款': 'longTermReceivables',
    '025长期股权投资': 'longTermEquityInvestment',
    '026投资性房地产': 'investmentRealEstate',
    '027固定资产': 'fixedAssets',
    '028在建工程': 'constructionInProgress',
    '029工程物资': 'engineerMaterial',
    '030固定资产清理': 'fixedAssetsCleanUp',
    '031生产性生物资产': 'productiveBiologicalAssets',
    '032油气资产': 'oilAndGasAssets',
    '033无形资产': 'intangibleAssets',
    '034开发支出': 'developmentExpenditure',
    '035商誉': 'goodwill',
    '036长期待摊费用': 'longTermDeferredExpenses',
    '037递延所得税资产': 'deferredIncomeTaxAssets',
    '038其他非流动资产': 'otherNonCurrentAssets',
    '039非流动资产合计': 'totalNonCurrentAssets',
    '040资产总计': 'totalAssets',
    # 2.2 负债
    # 2.2.1 流动负债
    '041短期借款': 'shortTermLoan',
    '042交易性金融负债': 'tradingFinancialLiabilities',
    '043应付票据': 'billsPayable',
    '044应付账款': 'accountsPayable',
    '045预收款项': 'advancedReceivable',
    '046应付职工薪酬': 'employeesPayable',
    '047应交税费': 'taxPayable',
    '048应付利息': 'interestPayable',
    '049应付股利': 'dividendPayable',
    '050其他应付款': 'otherPayable',
    '051应付关联公司款': 'interCompanyPayable',
    '052一年内到期的非流动负债': 'noncurrentLiabilitiesDueWithinOneYear',
    '053其他流动负债': 'otherCurrentLiabilities',
    '054流动负债合计': 'totalCurrentLiabilities',
    # 2.2.2 非流动负债
    '055长期借款': 'longTermLoans',
    '056应付债券': 'bondsPayable',
    '057长期应付款': 'longTermPayable',
    '058专项应付款': 'specialPayable',
    '059预计负债': 'estimatedLiabilities',
    '060递延所得税负债': 'defferredIncomeTaxLiabilities',
    '061其他非流动负债': 'otherNonCurrentLiabilities',
    '062非流动负债合计': 'totalNonCurrentLiabilities',
    '063负债合计': 'totalLiabilities',
    # 2.3 所有者权益
    '064实收资本（或股本）': 'totalShare',
    '065资本公积': 'capitalReserve',
    '066盈余公积': 'surplusReserve',
    '067减：库存股': 'treasuryStock',
    '068未分配利润': 'undistributedProfits',
    '069少数股东权益': 'minorityEquity',
    '070外币报表折算价差': 'foreignCurrencyReportTranslationSpread',
    '071非正常经营项目收益调整': 'abnormalBusinessProjectEarningsAdjustment',
    '072所有者权益（或股东权益）合计': 'totalOwnersEquity',
    '073负债和所有者（或股东权益）合计': 'totalLiabilitiesAndOwnersEquity',
    # 3. 利润表
    '074其中：营业收入': 'operatingRevenue',
    '075其中：营业成本': 'operatingCosts',
    '076营业税金及附加': 'taxAndSurcharges',
    '077销售费用': 'salesCosts',
    '078管理费用': 'managementCosts',
    '079堪探费用': 'explorationCosts',
    '080财务费用': 'financialCosts',
    '081资产减值损失': 'assestsDevaluation',
    '082加：公允价值变动净收益': 'profitAndLossFromFairValueChanges',
    '083投资收益': 'investmentIncome',
    '084其中：对联营企业和合营企业的投资收益': 'investmentIncomeFromAffiliatedBusinessAndCooperativeEnterprise',
    '085影响营业利润的其他科目': 'otherSubjectsAffectingOperatingProfit',
    '086三、营业利润': 'operatingProfit',
    '087加：补贴收入': 'subsidyIncome',
    '088营业外收入': 'nonOperatingIncome',
    '089减：营业外支出': 'nonOperatingExpenses',
    '090其中：非流动资产处置净损失': 'netLossFromDisposalOfNonCurrentAssets',
    '091加：影响利润总额的其他科目': 'otherSubjectsAffectTotalProfit',
    '092四、利润总额': 'totalProfit',
    '093减：所得税': 'incomeTax',
    '094加：影响净利润的其他科目': 'otherSubjectsAffectNetProfit',
    '095五、净利润': 'netProfit',
    '096归属于母公司所有者的净利润': 'netProfitsBelongToParentCompanyOwner',
    '097少数股东损益': 'minorityProfitAndLoss',

    # 4. 现金流量表
    # 4.1 经营活动 Operating
    '098销售商品、提供劳务收到的现金': 'cashFromGoodsSalesorOrRenderingOfServices',
    '099收到的税费返还': 'refundOfTaxAndFeeReceived',
    '100收到其他与经营活动有关的现金': 'otherCashRelatedBusinessActivitiesReceived',
    '101经营活动现金流入小计': 'cashInflowsFromOperatingActivities',
    '102购买商品、接受劳务支付的现金': 'buyingGoodsReceivingCashPaidForLabor',
    '103支付给职工以及为职工支付的现金': 'paymentToEmployeesAndCashPaidForEmployees',
    '104支付的各项税费': 'paymentsOfVariousTaxes',
    '105支付其他与经营活动有关的现金': 'paymentOfOtherCashRelatedToBusinessActivities',
    '106经营活动现金流出小计': 'cashOutflowsFromOperatingActivities',
    '107经营活动产生的现金流量净额': 'netCashFlowsFromOperatingActivities',
    # 4.2 投资活动 Investment
    '108收回投资收到的现金': 'cashReceivedFromInvestmentReceived',
    '109取得投资收益收到的现金': 'cashReceivedFromInvestmentIncome',
    '110处置固定资产、无形资产和其他长期资产收回的现金净额': 'disposalOfNetCashForRecoveryOfFixedAssetsIntangibleAssetsAndOtherLongTermAssets',
    '111处置子公司及其他营业单位收到的现金净额': 'disposalOfNetCashReceivedFromSubsidiariesAndOtherBusinessUnits',
    '112收到其他与投资活动有关的现金': 'otherCashReceivedRelatingToInvestingActivities',
    '113投资活动现金流入小计': 'cashinFlowsFromInvestmentActivities',
    '114购建固定资产、无形资产和其他长期资产支付的现金': 'cashForThePurchaseConstructionPaymentOfFixedAssetsIntangibleAssetsAndOtherLongTermAssets',
    '115投资支付的现金': 'cashInvestment',
    '116取得子公司及其他营业单位支付的现金净额': 'acquisitionOfNetCashPaidBySubsidiariesAndOtherBusinessUnits',
    '117支付其他与投资活动有关的现金': 'otherCashPaidRelatingToInvestingActivities',
    '118投资活动现金流出小计': 'cashOutflowsFromInvestmentActivities',
    '119投资活动产生的现金流量净额': 'netCashFlowsFromInvestingActivities',
    # 4.3 筹资活动 Financing
    '120吸收投资收到的现金': 'cashReceivedFromInvestors',
    '121取得借款收到的现金': 'cashFromBorrowings',
    '122收到其他与筹资活动有关的现金': 'otherCashReceivedRelatingToFinancingActivities',
    '123筹资活动现金流入小计': 'cashInflowsFromFinancingActivities',
    '124偿还债务支付的现金': 'cashPaymentsOfAmountBorrowed',
    '125分配股利、利润或偿付利息支付的现金': 'cashPaymentsForDistrbutionOfDividendsOrProfits',
    '126支付其他与筹资活动有关的现金': 'otherCashPaymentRelatingToFinancingActivities',
    '127筹资活动现金流出小计': 'cashOutflowsFromFinancingActivities',
    '128筹资活动产生的现金流量净额': 'netCashFlowsFromFinancingActivities',
    # 4.4 汇率变动
    '129四、汇率变动对现金的影响': 'effectOfForeignExchangRateChangesOnCash',
    '130四(2)、其他原因对现金的影响': 'effectOfOtherReasonOnCash',
    # 4.5 现金及现金等价物净增加
    '131五、现金及现金等价物净增加额': 'netIncreaseInCashAndCashEquivalents',
    '132期初现金及现金等价物余额': 'initialCashAndCashEquivalentsBalance',
    # 4.6 期末现金及现金等价物余额
    '133期末现金及现金等价物余额': 'theFinalCashAndCashEquivalentsBalance',
    # 4.x 补充项目 Supplementary Schedule：
    # 现金流量附表项目    Indirect Method
    # 4.x.1 将净利润调节为经营活动现金流量 Convert net profit to cash flow from operating activities
    '134净利润': 'netProfitFromOperatingActivities',
    '135资产减值准备': 'provisionForAssetsLosses',
    '136固定资产折旧、油气资产折耗、生产性生物资产折旧': 'depreciationForFixedAssets',
    '137无形资产摊销': 'amortizationOfIntangibleAssets',
    '138长期待摊费用摊销': 'amortizationOfLong-termDeferredExpenses',
    '139处置固定资产、无形资产和其他长期资产的损失': 'lossOfDisposingFixedAssetsIntangibleAssetsAndOtherLong-termAssets',
    '140固定资产报废损失': 'scrapLossOfFixedAssets',
    '141公允价值变动损失': 'lossFromFairValueChange',
    '142财务费用': 'financialExpenses',
    '143投资损失': 'investmentLosses',
    '144递延所得税资产减少': 'decreaseOfDeferredTaxAssets',
    '145递延所得税负债增加': 'increaseOfDeferredTaxLiabilities',
    '146存货的减少': 'decreaseOfInventory',
    '147经营性应收项目的减少': 'decreaseOfOperationReceivables',
    '148经营性应付项目的增加': 'increaseOfOperationPayables',
    '149其他': 'others',
    '150经营活动产生的现金流量净额2': 'netCashFromOperatingActivities2',
    # 4.x.2 不涉及现金收支的投资和筹资活动 Investing and financing activities not involved in cash
    '151债务转为资本': 'debtConvertedToCSapital',
    '152一年内到期的可转换公司债券': 'convertibleBondMaturityWithinOneYear',
    '153融资租入固定资产': 'leaseholdImprovements',
    # 4.x.3 现金及现金等价物净增加情况 Net increase of cash and cash equivalents
    '154现金的期末余额': 'cashEndingBal',
    '155现金的期初余额': 'cashBeginingBal',
    '156现金等价物的期末余额': 'cashEquivalentsEndingBal',
    '157现金等价物的期初余额': 'cashEquivalentsBeginningBal',
    '158现金及现金等价物净增加额': 'netIncreaseOfCashAndCashEquivalents',
    # 5. 偿债能力分析
    '159流动比率': 'currentRatio',  # 流动资产/流动负债
    '160速动比率': 'acidTestRatio',  # (流动资产-存货）/流动负债
    '161现金比率(%)': 'cashRatio',  # (货币资金+有价证券)÷流动负债
    '162利息保障倍数': 'interestCoverageRatio',  # (利润总额+财务费用（仅指利息费用部份）)/利息费用
    '163非流动负债比率(%)': 'noncurrentLiabilitiesRatio',
    '164流动负债比率(%)': 'currentLiabilitiesRatio',
    '165现金到期债务比率(%)': 'cashDebtRatio',  # 企业经营现金净流入/(本期到期长期负债+本期应付票据)
    '166有形资产净值债务率(%)': 'debtToTangibleAssetsRatio',
    '167权益乘数(%)': 'equityMultiplier',  # 资产总额/股东权益总额
    '168股东的权益/负债合计(%)': 'equityDebtRatio',  # 权益负债率
    '169有形资产/负债合计(%)': 'tangibleAssetDebtRatio ',  # 有形资产负债率
    '170经营活动产生的现金流量净额/负债合计(%)': 'netCashFlowsFromOperatingActivitiesDebtRatio',
    '171EBITDA/负债合计(%)': 'EBITDA/Liabilities',
    # 6. 经营效率分析
    # 销售收入÷平均应收账款=销售收入\(0.5 x(应收账款期初+期末))
    '172应收帐款周转率': 'turnoverRatioOfReceivable;',
    '173存货周转率': 'turnoverRatioOfInventory',
    # (存货周转天数+应收帐款周转天数-应付帐款周转天数+预付帐款周转天数-预收帐款周转天数)/365
    '174运营资金周转率': 'turnoverRatioOfOperatingAssets',
    '175总资产周转率': 'turnoverRatioOfTotalAssets',
    '176固定资产周转率': 'turnoverRatioOfFixedAssets',  # 企业销售收入与固定资产净值的比率
    '177应收帐款周转天数': 'daysSalesOutstanding',  # 企业从取得应收账款的权利到收回款项、转换为现金所需要的时间
    '178存货周转天数': 'daysSalesOfInventory',  # 企业从取得存货开始，至消耗、销售为止所经历的天数
    '179流动资产周转率': 'turnoverRatioOfCurrentAssets',  # 流动资产周转率(次)=主营业务收入/平均流动资产总额
    '180流动资产周转天数': 'daysSalesofCurrentAssets',
    '181总资产周转天数': 'daysSalesofTotalAssets',
    '182股东权益周转率': 'equityTurnover',  # 销售收入/平均股东权益
    # 7. 发展能力分析
    '183营业收入增长率(%)': 'operatingIncomeGrowth',
    '184净利润增长率(%)': 'netProfitGrowthRate',  # NPGR  利润总额－所得税
    '185净资产增长率(%)': 'netAssetsGrowthRate',
    '186固定资产增长率(%)': 'fixedAssetsGrowthRate',
    '187总资产增长率(%)': 'totalAssetsGrowthRate',
    '188投资收益增长率(%)': 'investmentIncomeGrowthRate',
    '189营业利润增长率(%)': 'operatingProfitGrowthRate',
    '190暂无': 'None1',
    '191暂无': 'None2',
    '192暂无': 'None3',
    # 8. 获利能力分析
    '193成本费用利润率(%)': 'rateOfReturnOnCost',
    '194营业利润率': 'rateOfReturnOnOperatingProfit',
    '195营业税金率': 'rateOfReturnOnBusinessTax',
    '196营业成本率': 'rateOfReturnOnOperatingCost',
    '197净资产收益率': 'rateOfReturnOnCommonStockholdersEquity',
    '198投资收益率': 'rateOfReturnOnInvestmentIncome',
    '199销售净利率(%)': 'rateOfReturnOnNetSalesProfit',
    '200总资产报酬率': 'rateOfReturnOnTotalAssets',
    '201净利润率': 'netProfitMargin',
    '202销售毛利率(%)': 'rateOfReturnOnGrossProfitFromSales',
    '203三费比重': 'threeFeeProportion',
    '204管理费用率': 'ratioOfChargingExpense',
    '205财务费用率': 'ratioOfFinancialExpense',
    '206扣除非经常性损益后的净利润': 'netProfitAfterExtraordinaryGainsAndLosses',
    '207息税前利润(EBIT)': 'EBIT',
    '208息税折旧摊销前利润(EBITDA)': 'EBITDA',
    '209EBITDA/营业总收入(%)': 'EBITDA/GrossRevenueRate',
    # 9. 资本结构分析
    '210资产负债率(%)': 'assetsLiabilitiesRatio',
    '211流动资产比率': 'currentAssetsRatio',  # 期末的流动资产除以所有者权益
    '212货币资金比率': 'monetaryFundRatio',
    '213存货比率': 'inventoryRatio',
    '214固定资产比率': 'fixedAssetsRatio',
    '215负债结构比': 'liabilitiesStructureRatio',
    '216归属于母公司股东权益/全部投入资本(%)': 'shareholdersOwnershipOfAParentCompany/TotalCapital',
    '217股东的权益/带息债务(%)': 'shareholdersInterest/InterestRateDebtRatio',
    '218有形资产/净债务(%)': 'tangibleAssets/NetDebtRatio',
    # 10. 现金流量分析
    '219每股经营性现金流(元)': 'operatingCashFlowPerShare',
    '220营业收入现金含量(%)': 'cashOfOperatingIncome',
    '221经营活动产生的现金流量净额/经营活动净收益(%)': 'netOperatingCashFlow/netOperationProfit',
    '222销售商品提供劳务收到的现金/营业收入(%)': 'cashFromGoodsSales/OperatingRevenue',
    '223经营活动产生的现金流量净额/营业收入': 'netOperatingCashFlow/OperatingRevenue',
    '224资本支出/折旧和摊销': 'capitalExpenditure/DepreciationAndAmortization',
    '225每股现金流量净额(元)': 'netCashFlowPerShare',
    '226经营净现金比率（短期债务）': 'operatingCashFlow/ShortTermDebtRatio',
    '227经营净现金比率（全部债务）': 'operatingCashFlow/LongTermDebtRatio',
    '228经营活动现金净流量与净利润比率': 'cashFlowRateAndNetProfitRatioOfOperatingActivities',
    '229全部资产现金回收率': 'cashRecoveryForAllAssets',
    # 11. 单季度财务指标
    '230营业收入': 'operatingRevenueSingle',
    '231营业利润': 'operatingProfitSingle',
    '232归属于母公司所有者的净利润': 'netProfitBelongingToTheOwnerOfTheParentCompanySingle',
    '233扣除非经常性损益后的净利润': 'netProfitAfterExtraordinaryGainsAndLossesSingle',
    '234经营活动产生的现金流量净额': 'netCashFlowsFromOperatingActivitiesSingle',
    '235投资活动产生的现金流量净额': 'netCashFlowsFromInvestingActivitiesSingle',
    '236筹资活动产生的现金流量净额': 'netCashFlowsFromFinancingActivitiesSingle',
    '237现金及现金等价物净增加额': 'netIncreaseInCashAndCashEquivalentsSingle',
    # 12.股本股东
    '238总股本': 'totalCapital',
    '239已上市流通A股': 'listedAShares',
    '240已上市流通B股': 'listedBShares',
    '241已上市流通H股': 'listedHShares',
    '242股东人数(户)': 'numberOfShareholders',
    '243第一大股东的持股数量': 'theNumberOfFirstMajorityShareholder',
    '244十大流通股东持股数量合计(股)': 'totalNumberOfTopTenCirculationShareholders',
    '245十大股东持股数量合计(股)': 'totalNumberOfTopTenMajorShareholders',
    # 13.机构持股
    '246机构总量（家）': 'institutionNumber',
    '247机构持股总量(股)': 'institutionShareholding',
    '248QFII机构数': 'QFIIInstitutionNumber',
    '249QFII持股量': 'QFIIShareholding',
    '250券商机构数': 'brokerNumber',
    '251券商持股量': 'brokerShareholding',
    '252保险机构数': 'securityNumber',
    '253保险持股量': 'securityShareholding',
    '254基金机构数': 'fundsNumber',
    '255基金持股量': 'fundsShareholding',
    '256社保机构数': 'socialSecurityNumber',
    '257社保持股量': 'socialSecurityShareholding',
    '258私募机构数': 'privateEquityNumber',
    '259私募持股量': 'privateEquityShareholding',
    '260财务公司机构数': 'financialCompanyNumber',
    '261财务公司持股量': 'financialCompanyShareholding',
    '262年金机构数': 'pensionInsuranceAgencyNumber',
    '263年金持股量': 'pensionInsuranceAgencyShareholfing',
    # 14.新增指标
    # [注：季度报告中，若股东同时持有非流通A股性质的股份(如同时持有流通A股和流通B股），取的是包含同时持有非流通A股性质的流通股数]
    '264十大流通股东中持有A股合计(股)': 'totalNumberOfTopTenCirculationShareholders',
    '265第一大流通股东持股量(股)': 'firstLargeCirculationShareholdersNumber',
    # [注：1.自由流通股=已流通A股-十大流通股东5%以上的A股；2.季度报告中，若股东同时持有非流通A股性质的股份(如同时持有流通A股和流通H股），5%以上的持股取的是不包含同时持有非流通A股性质的流通股数，结果可能偏大； 3.指标按报告期展示，新股在上市日的下个报告期才有数据]
    '266自由流通股(股)': 'freeCirculationStock',
    '267受限流通A股(股)': 'limitedCirculationAShares',
    '268一般风险准备(金融类)': 'generalRiskPreparation',
    '269其他综合收益(利润表)': 'otherComprehensiveIncome',
    '270综合收益总额(利润表)': 'totalComprehensiveIncome',
    '271归属于母公司股东权益(资产负债表)': 'shareholdersOwnershipOfAParentCompany ',
    '272银行机构数(家)(机构持股)': 'bankInstutionNumber',
    '273银行持股量(股)(机构持股)': 'bankInstutionShareholding',
    '274一般法人机构数(家)(机构持股)': 'corporationNumber',
    '275一般法人持股量(股)(机构持股)': 'corporationShareholding',
    '276近一年净利润(元)': 'netProfitLastYear',
    '277信托机构数(家)(机构持股)': 'trustInstitutionNumber',
    '278信托持股量(股)(机构持股)': 'trustInstitutionShareholding',
    '279特殊法人机构数(家)(机构持股)': 'specialCorporationNumber',
    '280特殊法人持股量(股)(机构持股)': 'specialCorporationShareholding',
    '281加权净资产收益率(每股指标)': 'weightedROE',
    '282扣非每股收益(单季度财务指标)': 'nonEPSSingle',
    '283最近一年营业收入(万元)': 'lastYearOperatingIncome',
    '284国家队持股数量(万股)': 'nationalTeamShareholding',
    # [注：本指标统计包含汇金公司、证金公司、外汇管理局旗下投资平台、国家队基金、国开、养老金以及中科汇通等国家队机构持股数量]
    '285业绩预告-本期净利润同比增幅下限%': 'PF_theLowerLimitoftheYearonyearGrowthofNetProfitForThePeriod',
    # [注：指标285至294展示未来一个报告期的数据。例，3月31日至6月29日这段时间内展示的是中报的数据；如果最新的财务报告后面有多个报告期的业绩预告/快报，只能展示最新的财务报告后面的一个报告期的业绩预告/快报]
    '286业绩预告-本期净利润同比增幅上限%': 'PF_theHigherLimitoftheYearonyearGrowthofNetProfitForThePeriod',
    '287业绩快报-归母净利润': 'PE_returningtotheMothersNetProfit',
    '288业绩快报-扣非净利润': 'PE_Non-netProfit',
    '289业绩快报-总资产': 'PE_TotalAssets',
    '290业绩快报-净资产': 'PE_NetAssets',
    '291业绩快报-每股收益': 'PE_EPS',
    '292业绩快报-摊薄净资产收益率': 'PE_DilutedROA',
    '293业绩快报-加权净资产收益率': 'PE_WeightedROE',
    '294业绩快报-每股净资产': 'PE_NetAssetsperShare',
    '295应付票据及应付账款(资产负债表)': 'BS_NotesPayableandAccountsPayable',
    '296应收票据及应收账款(资产负债表)': 'BS_NotesReceivableandAccountsReceivable',
    '297递延收益(资产负债表)': 'BS_DeferredIncome',
    '298其他综合收益(资产负债表)': 'BS_OtherComprehensiveIncome',
    '299其他权益工具(资产负债表)': 'BS_OtherEquityInstruments',
    '300其他收益(利润表)': 'IS_OtherIncome',
    '301资产处置收益(利润表)': 'IS_AssetDisposalIncome',
    '302持续经营净利润(利润表)': 'IS_NetProfitforContinuingOperations',
    '303终止经营净利润(利润表)': 'IS_NetProfitforTerminationOperations',
    '304研发费用(利润表)': 'IS_R&DExpense',
    '305其中:利息费用(利润表-财务费用)': 'IS_InterestExpense',
    '306其中:利息收入(利润表-财务费用)': 'IS_InterestIncome',
    '307近一年经营活动现金流净额': 'netCashFlowfromOperatingActivitiesinthepastyear',
    '308未知308': 'unknown308',
    '309未知309': 'unknown309',
    '310未知310': 'unknown310',
    '311未知311': 'unknown311',
    '312未知312': 'unknown312',
    '313未知313': 'unknown313',
    '314未知314': 'unknown314',
    '315未知315': 'unknown315',
    '316未知316': 'unknown316',
    '317未知317': 'unknown317',
    '318未知318': 'unknown318',
}

if __name__ == '__main__':
    # aaa = get_stock_daily_valuation(None, '2020-01-01', '2020-02-01', False)
    # bbb = get_stock_financial_indicators('000001', '2020-01-01', '2020-12-01', False)
    # ccc = get_stock_financial_derivative_indicators(stock_code=['600519', '000002', '000004', '000005', '000006', '000007'],
    #                                                 start_date='2020-01-01',
    #                                                 end_date='2021-01-01', only_latest=False,
    #                                                 select=['stock_code', 'report_date', 'operincome_yoy', 'netprofile_yoy', 'oacashnetps_ttm', 'roe_ttm'])
    # ddd = get_stock_financial_indicators(
    #     stock_code=['600519', '000002', '000004', '000005', '000006', '000007'],
    #     start_date='2020-01-01',
    #     end_date='2021-01-01',
    #     report_type=[10, 20],
    #     only_latest=False,
    #     select=['stock_code', 'report_date', 'report_type', 'net_profit', 'nonre_pl'])
    eee = get_stock_balance_indicators(
        stock_code=['600519', '000002', '000004', '000005', '000006', '000007'],
        start_date='2020-01-01',
        end_date='2021-01-01',
        report_type=[10, 20],
        only_latest=False,
        select=['stock_code', 'report_date', 'report_type', 'total_curliability', 'inventories'])
